<?php

namespace backend\components\actions;
use yii\helpers\Html;
use yii\base\Action;
use yii\web\Response;
use Yii;
/**
 * Description of ChangeValueAction
 * AJAX更新值的独立动作
 * @author zhuo bing
 */
class ChangeValueAction extends Action{
    /**
     *最后输出值的匿名函数
     * @var function 
     */
    public $outputValue = '';
    /**
     *最后输出消息的的匿名函数
     * @var function  
     */
    public $outputMessage = '';
    /**
     * @var array the options for error summary as supported by `options` param in `yii\helpers\Html::errorSummary()`
     */
    /**
     *要操作的模型类
     * @var type 
     */
    public $modelClass = '';
    /**
     *错误输出类型
     * @var type 
     */
    public $errorOptions = ['header' => ''];    
    public function run() {
        
        $request = Yii::$app->Request;
        Yii::$app->Response->format = Response::FORMAT_JSON;
        
        if ($request->post('hasEditable')) {
            $attribute = $request->post('editableAttribute');
            $key = $request->post('editableKey');
            $index = $key = $request->post('editableIndex');
            $modelClass = $this->modelClass;
            $model = $modelClass::findOne($request->post('editableKey'));
            $data[$model->formName()] = $request->post($model->formName())[$request->post('editableIndex')];
            $params = [$model,$attribute,$key,$index];
            
            if ($model->load($data) && $model->save()) {
                $value = static::parseValue($this->outputValue,$params);
                $message = static::parseValue($this->outputMessage,$params);
                return ['output' => $value, 'message' => $message];
            }else if($model->hasErrors()){
                return ['output' =>'' ,'message' => Html::errorSummary($model, $this->errorOptions)];
            }
            
        }
    }
    protected static function parseValue($var, $params = [])
    {
        return is_callable($var) ? call_user_func_array($var, $params) : $var;
    }    
}
